﻿using System.Globalization;
using System.Windows.Controls;

namespace DimensionsHelper.Client.ValidationRules;

public class DoubleValidationRule : ValidationRule
{
    public bool Positive { get; set; }

    public bool AllowZero { get; set; }


    public override ValidationResult Validate(object? value, CultureInfo cultureInfo)
    {
        double? dbValue = value switch
        {
            double d => d,
            string str when double.TryParse(str, cultureInfo, out double dbNum) => dbNum,
            _ => null
        };

        if (dbValue == null)
        {
            return new ValidationResult(false, "需要填写实数");
        }

        if (!AllowZero && dbValue == 0)
        {
            return new ValidationResult(false, "不能填写0");
        }

        if (Positive && dbValue < 0)
        {
            return new ValidationResult(false, "需要填写正数");
        }

        return ValidationResult.ValidResult;
    }
}